import React, {useEffect, useState} from "react";
import {Dimensions, StyleSheet, Text, TextInput, TouchableHighlight, View} from "react-native";
import {fontSize_10, fontSize_13, fontSize_14, fontSize_16} from "./theme";
import {
    addChainInfo,
    chainInfoType,
    getChainBaseByChainID,
    getChainInfo,
    getProviderUrlInfo,
    nowWallet, updateNowWallet
} from "./smartxL2Libs/L2_Data";
import {ping_async} from "./smartxL2Libs/ping";
import {BottomSheet} from "react-native-elements/dist/bottomSheet/BottomSheet";
import SimpleToast from "react-native-simple-toast";
import {getHeightByProviderUrl, getTranDetail_ETH, getTransaction} from "./smartxL2Libs/smartxL2Web3";
import {SvgXml} from "react-native-svg";
import {checkSvgXml} from "../libs/svgXml";

const {width,height,scale} = Dimensions.get("window");
let t: NodeJS.Timeout ;
let myProviderUrlInfoListOnLine ;
let userProviderUrlInfoListOnLine ;
const L2_NodeView = ({navigation,route}:any) => {

    const [myProviderUrlInfoList,setMyProviderUrlInfoList] = useState([{name:"",providerUrl:"",height:"",ping:""}]);

    const [userProviderUrlInfoList,setUserProviderUrlInfoList] = useState([{name:"",providerUrl:"",height:"",ping:""}]);

    const [selectedProviderUrl,setSelectedProviderUrl] = useState("")

    //显示添加节点输入框
    const [showInputContainer,setShowInputContainer] = useState(false)
    const [inputWord,setInputWord] = useState("")

    useEffect(()=>{
        let work = async () => {
            await initData()
            initPing()
            // t = setInterval(initPing,1.5*1000)
        }
        work()
        return () => {
            clearInterval(t)
        }
    },[])
    const initData = async () => {
        let chainBaseInfo = await getChainBaseByChainID(nowWallet.chainID);
        let chainInfo = await getChainInfo(nowWallet.chainID)
        navigation.setOptions({
            title:chainBaseInfo?.name
        })
        console.log(`chainInfo`,chainInfo)
        let myProviderUrlInfoListTemp = await getProviderUrlInfoList(chainInfo.providerUrlList,chainBaseInfo?.name || '')
        console.log(`myProviderUrlInfoListTemp`,myProviderUrlInfoListTemp)
        myProviderUrlInfoListOnLine = [...myProviderUrlInfoListTemp];
        setMyProviderUrlInfoList(myProviderUrlInfoListTemp)
        let userProviderUrlInfoListTemp = await getProviderUrlInfoList(chainInfo.userProviderUrlList || [],"");
        userProviderUrlInfoListOnLine = [...userProviderUrlInfoListTemp]
        setUserProviderUrlInfoList(userProviderUrlInfoListTemp)
        setSelectedProviderUrl(chainInfo.selectedProviderUrl)
    }
    const getProviderUrlInfoList = async (providerUrlList:string[],name:string) => {
        let myProviderUrlInfoListTemp = []
        console.log(providerUrlList.length)
        for(let i = 0 ; i < providerUrlList.length ; i++)
        {
            let providerUrl = providerUrlList[i];
            console.log(providerUrl)
            let providerUrlInfo = await getProviderUrlInfo(providerUrl);
            console.log(providerUrlInfo)
            if(providerUrlInfo)
            {
                if(name)
                {
                    providerUrlInfo.name=`${name}-${i+1}`
                }
                let myProviderUrlInfo = {
                    height: "",
                    ping: "",
                    ...providerUrlInfo
                };
                myProviderUrlInfoListTemp.push(myProviderUrlInfo);
            }
        }
        return myProviderUrlInfoListTemp;
    }
    const initPing = async () => {
        console.log(`initPing`)
        console.log(myProviderUrlInfoListOnLine,userProviderUrlInfoListOnLine)
        let again = false;
        let myProviderUrlInfoListTemp = [...myProviderUrlInfoListOnLine];
        for(let i = 0 ; i < myProviderUrlInfoListTemp.length ; i++)
        {
            let ping = await getPingOfUrl_ms(myProviderUrlInfoListTemp[i].providerUrl)
            let heightTemp = await getHeightByProviderUrl(myProviderUrlInfoListTemp[i].providerUrl);
            if(ping && Number(heightTemp)>0)
            {
                myProviderUrlInfoListTemp[i].ping = ping.toFixed(2);
                if(myProviderUrlInfoListTemp[i].height && (Number(myProviderUrlInfoListTemp[i].height) > Number(heightTemp)))
                {
                    continue;
                }
                myProviderUrlInfoListTemp[i].height = heightTemp;
            }
            else
            {
                myProviderUrlInfoListTemp[i].ping = undefined;
                again = true;
            }
        }
        let userProviderUrlInfoListTemp = [...userProviderUrlInfoListOnLine];

        for(let i = 0 ; i < userProviderUrlInfoListTemp.length ; i++)
        {
            let ping = await getPingOfUrl_ms(userProviderUrlInfoListTemp[i].providerUrl)
            let heightTemp = await getHeightByProviderUrl(userProviderUrlInfoListTemp[i].providerUrl);
            if(ping && Number(heightTemp)>0)
            {
                userProviderUrlInfoListTemp[i].ping = ping.toFixed(2);
                if(userProviderUrlInfoListTemp[i].height && (Number(userProviderUrlInfoListTemp[i].height) > Number(heightTemp)))
                {
                    continue;
                }
                userProviderUrlInfoListTemp[i].height = heightTemp;
            }
            else
            {
                userProviderUrlInfoListTemp[i].ping = undefined;
            }
        }
        console.log(myProviderUrlInfoListTemp)
        myProviderUrlInfoListOnLine = myProviderUrlInfoListTemp;
        userProviderUrlInfoListOnLine = userProviderUrlInfoListTemp
        setUserProviderUrlInfoList([...userProviderUrlInfoListTemp])
        setMyProviderUrlInfoList([...myProviderUrlInfoListTemp])
    }
    const getPingOfUrl_ms = async (providerUrl: string) => {
        try {
            let data = providerUrl.split(":");
            console.log(data.length)
            if (data.length === 2) {
                if (providerUrl.indexOf("https") === 0) {
                    data = [providerUrl.replace("https://",""), "443"]
                } else if (providerUrl.indexOf("http") === 0) {
                    data = [providerUrl.replace("http://",""), "80"]
                }
            } else if (data.length === 3) {
                data = [data[1].replace("//", ""), data[2]]
            } else {
                return;
            }
            let probeRes = await ping_async({
                address: data[0],
                port: Number(data[1]),
                attempts: 1,
                timeout: 3000
            });
            console.log(`probeRes`, probeRes)
            if (typeof probeRes.max !== "number") {
                console.log(typeof probeRes.max)
                return null;
            }
            return probeRes.avg;
        }catch (e) {
            return null
        }
    }
    const addNewProviderUrl = async () => {
        try {
            let url = inputWord;
            if (inputWord.indexOf("https://") !== 0 && inputWord.indexOf("http://") !== 0) {
                url = "https://" + url;
            }
            let pingTemp = await getPingOfUrl_ms(url);
            if (pingTemp) {
                let chainInfoTemp: chainInfoType = {
                    chainID: nowWallet.chainID,
                    providerUrlList: [],
                    walletList: [],
                    selectedProviderUrl: "",
                    userProviderUrlList: [url]
                };
                let res = await addChainInfo(chainInfoTemp)
                console.log(res)
                if (!res.success) {
                    SimpleToast.show(res.falseReason)
                }
                await initData()
                return;
            }
            SimpleToast.show("链接网络错误")
        }
        catch (e) {
            console.log(e)
        }
        finally {
            setShowInputContainer(false)
        }


    }
    return (
        <View style={styles.container}>
            <View style={styles.TipContainer}>
                <View style={styles.Tip1}>
                    <Text style={[styles.TipText]}>节点速度</Text>
                    <View style={styles.dot_green}/>
                    <Text style={[styles.ML_5,styles.TipText]}>快</Text>
                    <View style={styles.dot_yellow}/>
                    <Text style={[styles.ML_5,styles.TipText]}>中</Text>
                    <View style={styles.dot_red}/>
                    <Text style={[styles.ML_5,styles.TipText]}>慢</Text>
                </View>
                <Text style={[styles.TipText,styles.MT_10]}>
                    区块高度:高度值越大，代表节点数据同步更完善，其稳定性更好。在节点速度差不多的情况下，选择高度值大的节点，体验更好
                </Text>
            </View>
            <Text style={[styles.TipText,{width:'100%',marginTop:20}]}>推荐节点</Text>
            <View style={styles.NodeContainer}>
                {
                    myProviderUrlInfoList.map((item,index)=>(
                        <TouchableHighlight underlayColor={"transparent"}
                                            onPress={async ()=>{
                                                if(item.providerUrl===selectedProviderUrl)
                                                {
                                                    await initPing()
                                                    return
                                                }
                                                await addChainInfo({chainID:nowWallet.chainID,providerUrlList:[],walletList:[],selectedProviderUrl:item.providerUrl,userProviderUrlList:[]})
                                                setSelectedProviderUrl(item.providerUrl)
                                                await updateNowWallet({address:nowWallet.address,providerUrl:item.providerUrl,chainID:nowWallet.chainID})
                                                await initPing()
                                            }}
                                            key={`myProviderUrlInfoList_${index}`}>
                            <View style={styles.NodeItem} >
                            <View>
                                {
                                    item.name?
                                        <View style={{flexDirection:"row",alignItems:"center"}}>
                                            <Text style={styles.NodeInfoTitle}>{item.name}</Text>
                                            {
                                                item.providerUrl===selectedProviderUrl?
                                                    <SvgXml xml={checkSvgXml("blue")} style={{marginLeft:15}} width={fontSize_14} height={fontSize_14}/>
                                                    :null
                                            }
                                        </View>
                                        :null
                                }
                                {
                                    item.name?
                                        <Text style={styles.NodeInfoContent}>{item.providerUrl}</Text>
                                        :
                                        <Text style={styles.NodeInfoTitle}>{item.providerUrl}</Text>
                                }
                            </View>
                            {
                                item.ping!==undefined?
                                    <View >
                                        <View style={styles.NodePingContainer}>
                                            <Text style={styles.NodeInfoTitle}>{item.ping?`${item.ping} ms`:""} </Text>
                                            {
                                                item.ping?
                                                    <View style={item.ping>300?styles.dot_red:(item.ping>150?styles.dot_yellow:styles.dot_green)}/>
                                                    :
                                                    null
                                            }
                                        </View>
                                        <View style={styles.NodeHeightContainer}>
                                            <Text style={styles.NodeInfoContent}>{item.ping?`区块高度 ${item.height}`:""}</Text>
                                        </View>
                                    </View>
                                    :
                                    <View style={{flexDirection:"row",alignItems:"center"}}>
                                        <Text style={styles.NodeInfoTitle}>出错了</Text>
                                        <View style={styles.dot_red}/>
                                    </View>
                            }
                        </View>
                        </TouchableHighlight>
                    ))
                }
            </View>
            {
                userProviderUrlInfoList.length?
                    <View style={styles.container} >
                        <Text style={[styles.TipText,{width:'100%',marginTop:20}]}>自定义节点</Text>
                        <View style={styles.NodeContainer}>
                            {
                                userProviderUrlInfoList.map((item,index)=>(
                                    <TouchableHighlight underlayColor={"transparent"} onPress={async ()=>{
                                        if(item.providerUrl===selectedProviderUrl)
                                        {
                                            await initPing()
                                            return
                                        }
                                        await addChainInfo({chainID:nowWallet.chainID,providerUrlList:[],walletList:[],selectedProviderUrl:item.providerUrl,userProviderUrlList:[]})
                                        setSelectedProviderUrl(item.providerUrl)
                                        await updateNowWallet({address:nowWallet.address,providerUrl:item.providerUrl,chainID:nowWallet.chainID})
                                        await initPing()
                                    }} key={`userProviderUrlInfoList_${index}`}>
                                        <View style={styles.NodeItem} >
                                        <View>
                                            <View style={{flexDirection:"row",alignItems:"center"}}>
                                                <Text style={styles.NodeInfoTitle}>{item.providerUrl}</Text>
                                                {
                                                    item.providerUrl===selectedProviderUrl?
                                                        <SvgXml xml={checkSvgXml("blue")} style={{marginLeft:15}} width={fontSize_14} height={fontSize_14}/>
                                                        :null
                                                }
                                            </View>

                                        </View>
                                        {
                                            item.ping!==undefined?
                                                <View >
                                                    <View style={styles.NodePingContainer}>
                                                        <Text style={styles.NodeInfoTitle}>{item.ping?`${item.ping} ms`:""} </Text>
                                                        {
                                                            item.ping?
                                                                <View style={item.ping>300?styles.dot_red:(item.ping>150?styles.dot_yellow:styles.dot_green)}/>
                                                                :
                                                                null
                                                        }
                                                    </View>
                                                    <View style={styles.NodeHeightContainer}>
                                                        <Text style={styles.NodeInfoContent}>{item.ping?`区块高度 ${item.height}`:""}</Text>
                                                    </View>
                                                </View>
                                                :
                                                <View style={{flexDirection:"row",alignItems:"center"}}>
                                                    <Text style={styles.NodeInfoTitle}>出错了</Text>
                                                    <View style={styles.dot_red}/>
                                                </View>
                                        }
                                    </View>
                                    </TouchableHighlight>
                                ))
                            }
                        </View>
                    </View>
                    :null
            }
            <TouchableHighlight
                underlayColor={'transparent'}
                onPress={()=>{
                    setShowInputContainer(true)
                }}
                style={{marginTop:20,marginBottom:20}}
                >
                <Text style={[styles.NodeInfoTitle,{color:"#2970cc"}]}>添加自定义节点</Text>
            </TouchableHighlight>

            <BottomSheet
                modalProps={{animationType:"fade"}}
                isVisible={showInputContainer}
            >
                <View style={{width:width,height:height-1,backgroundColor: 'rgba(0.5, 0.25, 0, 0.2)'}}>
                    <TouchableHighlight
                        underlayColor={"rgba(0.5, 0.25, 0, 0.2)"}
                        onPress={()=>{
                            setInputWord("")
                            setShowInputContainer(false)
                        }}
                        style={{flex:1,backgroundColor:"rgba(0.5, 0.25, 0, 0.2)",alignItems:"center",justifyContent:"center"}}
                    >
                        <TouchableHighlight underlayColor={"rgba(0.5, 0.25, 0, 0.2)"} style={{width:"100%"}}>
                            <View style={{borderRadius:5,width:"100%",alignItems:"center"}}>
                                <View style={{
                                    width:"80%",
                                    backgroundColor:"#f5f6f8",
                                    padding:20,
                                    borderTopRightRadius:5,
                                    borderTopLeftRadius:5,
                                    alignItems:"center",
                                    borderBottomWidth:1/scale,
                                    borderBottomColor:"#b4b5b7",
                                }}>
                                    <Text style={{fontSize:fontSize_16,fontWeight:"bold",marginBottom:20}}>添加自定义节点</Text>
                                    <View style={{
                                        width:"100%",
                                        backgroundColor:"white",
                                        padding:5,
                                        borderRadius:5,
                                        borderWidth:1/scale,
                                        borderColor:"#bebfc1"}}>
                                        <TextInput
                                            placeholder={""}
                                            multiline={true}
                                            style={{
                                                width:"80%",
                                                fontSize:fontSize_16,
                                                padding:10,
                                                minHeight:70,
                                                textAlign:"left",
                                                textAlignVertical:"top"
                                            }}
                                            onChangeText={(value)=>{setInputWord(value.trim())}}
                                        />
                                    </View>
                                </View>
                                <View style={{
                                    width:"80%",
                                    height:45,
                                    backgroundColor:"#f5f6f8",
                                    borderBottomRightRadius:5,
                                    borderBottomLeftRadius:5,
                                    flexDirection:"row"
                                }}>
                                    <TouchableHighlight underlayColor={"#f5f6f8"} style={{flex:1,alignItems:"center",justifyContent:"center",borderRightWidth:1/scale,borderRightColor:"#b4b5b7"}}
                                                        onPress={()=>{
                                                            setInputWord("")
                                                            setShowInputContainer(false)
                                                        }}>
                                        <Text style={{fontSize:fontSize_14}}>
                                            取消
                                        </Text>
                                    </TouchableHighlight>
                                    <TouchableHighlight underlayColor={"#f5f6f8"} style={{flex:1,alignItems:"center",justifyContent:"center"}} onPress={()=>{
                                        addNewProviderUrl()
                                    }}>
                                        <Text style={{fontSize:fontSize_14}}>
                                            确认
                                        </Text>
                                    </TouchableHighlight>
                                </View>
                            </View>
                        </TouchableHighlight>
                    </TouchableHighlight>
                </View>
            </BottomSheet>

        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        padding:10,
        backgroundColor: "#f6f6f6"
    },
    dot_green: {
        width: 6,
        height: 6,
        borderRadius: 5,
        backgroundColor: "green",
        marginLeft: 15
    },
    dot_red: {
        width: 6,
        height: 6,
        borderRadius: 5,
        backgroundColor: "red",
        marginLeft: 15
    },
    dot_yellow: {
        width: 6,
        height: 6,
        borderRadius: 5,
        backgroundColor: "#ff6808",
        marginLeft: 15
    },
    TipContainer:{
        width:"100%",
        padding:8,
        backgroundColor:"white"
    },
    Tip1:{
        flexDirection:"row",
        alignItems:"center"
    },
    ML_5:{
        marginLeft:5,
    },
    MT_10:{
        marginTop:10,
    },
    TipText:{
        fontSize:fontSize_13,
        color:"#a0a0a0",
        lineHeight:20,
    },
    NodeContainer:{
        width:width,
        // marginLeft:-10,
        padding:8,
        backgroundColor:"white",
        paddingTop:0,
        paddingBottom:0
    },
    NodeItem:{
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"space-between",
        paddingTop:12,
        paddingBottom:12,
        borderBottomWidth:1/scale,
        borderBottomColor:"#ececec"
    },
    NodeInfoTitle:{
        fontSize:fontSize_14,
        color:"black",
        maxWidth:width*0.8
    },
    NodeInfoContent:{
        fontSize:fontSize_10,
        color:"#a0a0a0",
        maxWidth:width*0.8
    },
    NodePingContainer:{
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"flex-end"
    },
    NodeHeightContainer:{
        flexDirection:"row",
        alignItems:"center"
    },
})
export default L2_NodeView;


